package Presenter;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import Models.InvPSOLines;

public class InvPSOLinePresenter extends AbstractPresenter<InvPSOLines> {
	final String SINGLEITEM = "invPSOLines";
	final String MULTIITEM = "invPSOLiness";
	
	public InvPSOLines getEmptyEntity(){
		InvPSOLines entity = new InvPSOLines();
		return entity;
	}
	
	public ArrayList<InvPSOLines> tryJSONParseArray(String input){
		return super.doJSONParseArray(input, SINGLEITEM, MULTIITEM);
	}
	
	public InvPSOLines tryJSONParse(String input){
		return super.doJSONParse(input, SINGLEITEM);
	}
	
	public InvPSOLines createItemFromJSONObject(JSONObject jsonObject){
		InvPSOLines item = new InvPSOLines();
		try{
			item.setId(jsonObject.getInt("invPSOID"));
			item.setPriceOverRide(jsonObject.getDouble("invPSOPriceOver"));
			item.setQty(jsonObject.getInt("invPSOQty"));
			item.setQtyLeft(jsonObject.getInt("invPSOQtyLeft"));
			item.setSold(jsonObject.getBoolean("invPSOSold"));
			
			DiscountCodePresenter dcPresenter = new DiscountCodePresenter();
			JSONObject jsonDisc = jsonObject.getJSONObject("invPSOdisc");
			item.setDiscount(dcPresenter.createItemFromJSONObject(jsonDisc));
			
			SuppliesPresenter supplyPresenter = new SuppliesPresenter();
			JSONObject jsonSupply = jsonObject.getJSONObject("invPSOSupplyID");
			item.setSupply(supplyPresenter.createItemFromJSONObject(jsonSupply));
			
			return item;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(InvPSOLines item){
		try{
			JSONObject json = new JSONObject();
			json.put("invPSOID", item.getId());
			json.put("invPSOPriceOver", item.getPriceOverRide());
			json.put("invPSOQty", item.getQty());
			json.put("invPSOQtyLeft", item.getQtyLeft());
			json.put("invPSOSold", item.isSold());

			if(item.getDiscount()!=null){
				DiscountCodePresenter presenter = new DiscountCodePresenter();
				json.put("invPSOdisc", presenter.createJSON(item.getDiscount()));
			} else {
				json.put("invPSOdisc", JSONObject.NULL);
			}
			
			SuppliesPresenter supplyPresenter = new SuppliesPresenter();
			json.put("invPSOSupplyID", supplyPresenter.createJSON(item.getSupply()));
			
			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
}
